import java.util.Scanner;

class a {
    // 定义栈节点类
    private static class StackNode {
        int data;
        StackNode next;
        public StackNode(int data) {
            this.data = data;
            this.next = null;
        }
    }

    private StackNode top; // 栈顶指针
    // 初始化栈
    public a() {
        top = null;
    }

    // 判断栈是否为空
    public boolean isEmpty() {
        return top == null;
    }

    // 入栈操作
    public void push(int value) {
        StackNode newNode = new StackNode(value);
        newNode.next = top;
        top = newNode;
    }

    // 出栈操作
    public int pop() {
        if (isEmpty()) {
            System.out.println("栈为空，无法执行出栈操作");
            return -1;
        }
        int value = top.data;
        top = top.next;
        return value;
    }

    // 获取栈顶元素
    public int peek() {
        if (isEmpty()) {
            System.out.println("栈为空");
            return -1;
        }
        return top.data;
    }
    // 打印栈内容（从栈顶到栈底）
    public void display() {
        if (isEmpty()) {
            System.out.println("栈为空");
            return;
        }
        StackNode current = top;
        System.out.print("此时链栈元素从栈顶到栈底依次为：");
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        a stack = new a();
        System.out.println("请输入要建立的栈中的元素个数：");
        int n = scanner.nextInt();
        for (int i = 1; i <= n; i++) {
            System.out.println("输入第" + i + "个入栈的元素：");
            int element = scanner.nextInt();
            stack.push(element);//将元素入栈
        }
        System.out.println("读取栈顶元素,当前栈顶元素为：" + stack.peek());
        System.out.print("创建的链栈元素从栈顶到栈底依次为：");
        StackNode temp = stack.top;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
        System.out.println("输入一个要进栈的元素：");
        int newElement = scanner.nextInt();
        stack.push(newElement);//将新元素入栈
        System.out.println("读取栈顶元素,当前栈顶元素为：" + stack.peek());
        stack.pop();//执行出栈操作
        System.out.println("执行一次出栈操作后,当前栈顶元素为：" + stack.peek());
        stack.display();//打印出栈后的栈中所有元素
        scanner.close();
        System.out.println("-------------------------------------");
    }
}